var tabbarJs = require("../tabbar/tabbar.js");
var init = tabbarJs.init;
var onTabbarItemTap = tabbarJs.onTabbarItemTap;
var app = getApp();
var modelImgUrl = '../../images/';
var Tools = require('../../js/Tools.js');
var RequestManager = require('../../js/requestsMode.js');
var SessionManager = require('../../js/session.js');
var Constans = require('../../js/constants.js');

var requestMode = require('../../js/requestsMode.js');
var session = require('../../js/session.js');
var constants = require('../../js/constants.js');

function getWindowSize(){
    var windowWidth=0;
    var windowHeight=0;
    wx.getSystemInfo({
        success: function (res) {
            windowWidth = res.windowWidth;
            windowHeight = res.windowHeight;
        }
    });
    return {
        "windowWidth" : windowWidth,
        "windowHeight" : windowHeight
    }
}
var windowWidth= getWindowSize().windowWidth;
var windowHeight= getWindowSize().windowHeight;
var translaTionY=windowHeight;
var PageData = {
    data: {
        currentPage : 1,
        totalPage : 0,
        jhDataForTabbar :Tools.tabBarItems(3,0),
        delAnimation:'transform:translateX('+-(windowWidth+100)+'px);transition:all 0.3s;',
        marginAnimation:'',
        joinCar:modelImgUrl+'joinCar_now.png',
        radio:modelImgUrl+'carChoseStyle.png',
        items: [],
        willDelId:null,
        startX: 0, //开始坐标
        startY: 0,
        ifShowAlert:false,
        'alertBgShow':'display:none',
        'alert_transition':'translateY('+translaTionY+'px);transition: all 0s;',
        'close_alertImg':modelImgUrl+'close_alert.png',
        'buttonReduceImg' : modelImgUrl+'reduce.png',
        'buttonAddImg': modelImgUrl+'add.png',
        'sd_img' : modelImgUrl+ 'details_shopping.png',
        notShopping:modelImgUrl+'notOrder.png',
        listLength : 0,
        ///弹窗需要
        hasNumber:1,        //弹窗商品数量
        chooseShopName : "",
        all_price : "",
        allType : [],
        selectShopDetailInfo : {}
    },


    onTabbarItemTap:onTabbarItemTap,

    onLoad: function () {
        Tools.requestBuyCarCount(false,this,3);
        this.requestAlwasyBuyList();
    },
    ///下拉刷新
    onPullDownRefresh : function () {
      this.setData(
          {
              currentPage : 1
          }
      );
      this.requestAlwasyBuyList();
    },
    ///上拉加载更多
    onReachBottom : function () {
        if (this.data.currentPage >= this.data.totalPage)
        {
            return;
        }
        this.setData(
            {
                currentPage : this.data.currentPage + 1
            }
        );
        this.requestAlwasyBuyList();
    },
    ///请求购物车列表数据
    requestAlwasyBuyList : function () {
        Tools.showLoaddingDefault();
        if (this.data.currentPage == 1) {
            this.setData({
                    items : []
                });
        }
        let that = this;
        RequestManager.sendRequest("always-buy/list","POST",{"page":this.data.currentPage,"page_size":Constans.size},{sKey:SessionManager.get("sKey")}).then(
            function (requestSucess) {
                let resultCode = requestSucess.data.code;
                if (resultCode == 200) {
                    ///请求成功
                    Tools.hideLoaddingToast();
                    var resultArray = that.data.items;
                    let listData = requestSucess.data.data.list;
                    for (var tempIndex = 0;tempIndex < listData.length;tempIndex++) {
                        resultArray.push(listData[tempIndex]);
                    }
                    that.setData({
                            items : resultArray,
                            listLength : resultArray.length,
                            totalPage : requestSucess.data.data.page_total
                        });
                }else {
                    ///请求失败
                    Tools.showErrorToast(requestSucess.data.message);
                }
            },function (requestWrong) {
                Tools.showWrongNetWorkToast();
            }
        );
    },
    touchstart: function (e) {
        this.data.items.forEach(function (v, i) {
            if (v.isTouchMove)
                v.isTouchMove = false;
        });
        this.setData({
            startX: e.changedTouches[0].clientX,
            startY: e.changedTouches[0].clientY,
            items: this.data.items
        })
    },
    touchmove: function (e) {
        let that = this,
            index = e.currentTarget.dataset.index,//当前索引
            startX = that.data.startX,//开始X坐标
            startY = that.data.startY,//开始Y坐标
            touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
            touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
            angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
        that.data.items.forEach(function (v, i) {
            v.isTouchMove = false;
            //滑动超过30度角 return
            if (Math.abs(angle) > 30) return;
            if (i == index) {
                if (touchMoveX > startX){  //右滑
                    v.isTouchMove = false;
                }
                else {
                    v.isTouchMove = true
                }
            }
        });
        that.setData({
            items: that.data.items
        })
    },
    angle: function (start, end) {
        let _X = end.X - start.X,
            _Y = end.Y - start.Y;
        //返回角度 /Math.atan()返回数字的反正切值
        return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    seeTheDetailed:function(e){
        //查看详情
        let oid= e.currentTarget.dataset.id;
        wx.navigateTo({
            url:'../type/detailed/detailed?id='+oid
        });
    },
    del: function (e) {
        let that = this;
        let indexOfDel = e.currentTarget.dataset.index;
        let idOfDel = e.currentTarget.dataset.id;
        Tools.showLoaddingDefault();
        requestMode.sendRequest("always-buy/remove","POST",{id:idOfDel},{sKey:session.get("sKey")}).then(
          function (requestSucess) {
              let resultCode = requestSucess.data.code;
              if (resultCode == 200) {
                  ///删除长购清单成功
                  Tools.hideLoaddingToast();
                  that.deleteSuccessAnimation(indexOfDel,idOfDel);
              }else {
                  ///出错了
                  Tools.showErrorToast(requestSucess.data.message);
              }
          },function (requestWrong)
            {
                Tools.showWrongNetWorkToast();
            }
        );
    },
    ///删除之后的动画
    deleteSuccessAnimation : function (indexOfDel,idOfDel) {
        let that = this;
        let newData = that.data.items;
        let delNextBrotherId = '';
        if(newData.length ==1){
            delNextBrotherId = '';
        }else{
            if(indexOfDel == newData.length-1){
                delNextBrotherId = ''
            }else{
                delNextBrotherId = newData[indexOfDel+1]['id'];
            }
        }
        this.setData({
            willDelId:idOfDel,
            delNextBrotherId:delNextBrotherId
        });
        setTimeout(function(){
            that.setData({
                marginAnimation: 'margin-top:-252rpx;transition:margin-top 0.2s linear;'
            })
        },500);
        setTimeout(function(){
            newData.splice(indexOfDel, 1);
            that.setData({
               listLength : newData.length
            });
            that.setData({
                marginAnimation: '',
                items: newData
            });
        },720);
    },
    /*弹窗*/
    body_closeAlert:function(){
        const   This=this;
        const intHeight=getWindowSize().windowHeight;
        This.setData({
            alertllHeight:intHeight
        });
        This.setData({
            'alert_transition':'translateY('+intHeight+'px);transition: all 0.5s;'
        });
        setTimeout(function(){
            This.setData({
                ifShowAlert:false
            })
        },10);
        setTimeout(function(){
            This.setData({
                alertBgShow:'display:none'
            });
        },300)
    },
    close_alert:function(){
        const   This=this;
        const intHeight=getWindowSize().windowHeight;
        This.setData({
            alertllHeight:intHeight
        });
        This.setData({
            'alert_transition':'translateY('+intHeight+'px);transition: all 0.5s;'
        });
        setTimeout(function(){
            This.setData({
                ifShowAlert:false
            })
        },10);
        setTimeout(function(){
            This.setData({
                alertBgShow:'display:none'
            });
        },300)
    },
    closeBuyAlertView: function() {
        let that = this;
        setTimeout(function(){
            that.setData({
                ifShowAlert:false
            })
        },10);
        setTimeout(function(){
            that.setData({
                alertBgShow:'display:none'
            });
        },300);
    },
    ///获取当前选中商品对应规格的价格
    getCurrentPerPrice : function () {
        const allType=this.data.allType;
        var currentPrice = 0.0;
        for(var i=0;i<allType.length;i++){
            if(allType[i].class == 'chose'){
                 return allType[i].space_price;
            }
        }
    },
    choseThisType:function(e){
        var clickIndex=e.currentTarget.dataset.index;
        const allType=this.data.allType;
        for(var i=0;i<allType.length;i++){
            if(i==clickIndex){
                allType[i].class='chose';
            }else{
                allType[i].class='notChose';
            }
        }
        this.setData({
            'allType':allType,
        })
        this.reloadPrice();
    },
    ///数量增加
    tap_add:function(){
        const This=this;
        This.setData({
            addClick:true
        });

        if(This.data.hasNumber>=1){
            This.setData({
                hasNumber:parseInt(This.data.hasNumber)+1,
            });
            this.reloadPrice();
        }
        setTimeout(function(){
            This.setData({
                addClick:false
            });
        },200)
    },
    ///刷新弹窗价格
    reloadPrice : function () {
        var  perPrice = this.getCurrentPerPrice();
        var totalPrice = this.data.hasNumber * perPrice;
        this.setData(
            {
                all_price : totalPrice.toFixed(2)
            }
        );
    },
    numberChange:function(e){
        const  This=this;
        This.setData({
            hasNumber:e.detail.value
        })
        this.reloadPrice();
    },
    tap_reduce:function(){
        if (this.data.hasNumber <= 1)
        {
            return;
        }
        let This=this;
        this.setData({
            reduceClick:true
        });
        if(this.data.hasNumber>1){
            This.setData({
                hasNumber:parseInt(This.data.hasNumber)-1
            });
            this.reloadPrice();
        }
        setTimeout(function(){
            This.setData({
                reduceClick:false
            });
        },200)
    },
    clickBuyCarEvent : function (shop) {
        let currentShop = shop.currentTarget.dataset.item;
        ///准备请求商品详情
        Tools.showLoaddingDefault();
        let that = this;
        requestMode.sendRequest("goods/detail","POST",{goods_id:currentShop.goods_id},{sKey:session.get("sKey")}).then(
            function (requestSucess)
            {
                Tools.hideLoaddingToast();
                let resultCode = requestSucess.data.code;
                if (resultCode == 200) {
                    ///请求详情成功
                    Tools.hideLoaddingToast();
                    let  resultData = requestSucess.data.data;
                    for (let tempIndex = 0;tempIndex < resultData.space.length; tempIndex++) {
                        if (tempIndex == 0) {
                            resultData.space[tempIndex].class = "chose";
                        }else {
                            resultData.space[tempIndex].class = "notChose";
                        }
                    }
                    if (resultData.space.length)
                    {
                        that.setData(
                            {
                                all_price : resultData.space[0].space_price
                            }
                        );
                    }
                    that.setData({
                            sd_img : resultData.img,
                            allType : resultData.space,
                            chooseShopId : resultData.id,
                            chooseShopStock : resultData.stock,
                            chooseShopName : resultData.name,
                            selectShopDetailInfo:resultData
                        }
                    );
                    that.pf_showAlertForBuy();
                }else
                {
                    Tools.showErrorToast(requestSucess.data.message);
                }
            },function (requestWrong)
            {
                Tools.showWrongNetWorkToast();
            }
        )
    },
    /*出现添加购物车购买弹窗*/
    pf_showAlertForBuy : function() {
        const   This=this;
        const intHeight=getWindowSize().windowHeight;
        This.setData({
            alertllHeight:intHeight,
            'alert_transition':'translateY('+intHeight+'px);transition: all 0s;'
        });
        This.setData({
            alertBgShow:'display:block'
        });
        setTimeout(function(){
            This.setData({
                ifShowAlert:true
            })
        },10);
        setTimeout(function(){
            This.setData({
                'alert_transition':'translateY('+0+'px);transition: all 0.2s;',
            })
        },10)
    },
    joinCar:function(e){
        wx.showToast({
            title: '请等待...',
            icon: 'loading',
            duration: 800
        });
        setTimeout(function(){
            wx.showToast({
                title: '加入购物车成功',
                icon: 'success',
                duration: 800
            })
        },800)
    },
    //加入购物车
    settingJoinCar:function(e){
        const  This=this;
        const intHeight=getWindowSize().windowHeight;
        This.setData({
            alertllHeight:intHeight
        });
        This.setData({
            'alert_transition':'translateY('+intHeight+'px);transition: all 0.5s;'
        });
        var space_id = "";
        for (var tempIndex = 0;tempIndex < this.data.allType.length;tempIndex++) {
            if(this.data.allType[tempIndex].class == 'chose')
            {
                //找到对应选中的那个规格
                space_id = this.data.allType[tempIndex].space_id;
                break;
            }
        }
        let that = this;
        Tools.showLoaddingDefault();
        ///网络请求加入购物车
        requestMode.sendRequest("shop-cart/add","POST",{goods_id:this.data.chooseShopId,number:this.data.hasNumber,space_id:space_id},{skey:session.get('sKey')}).then(
            function (sucessRes)
            {
                that.closeBuyAlertView();
                Tools.hideLoaddingToast();
                let responseCode = sucessRes.data.code;
                if(responseCode == 200)
                {
                    ///加入购物车成功
                    ///给购物车数量加1
                    getApp().buyCarCount += 1;
                    ///重新刷新tab上面的数量
                    Tools.requestBuyCarCount(false,that,1);
                    Tools.showSuccessInfoToast("已添加进购物车");
                }else
                {
                    ///加入购物车失败
                    Tools.showErrorToast(sucessRes.data.message);
                }

            },function(wrongNetRes)
            {
                Tools.showWrongNetWorkToast();
                that.closeBuyAlertView();
            }
        );
    },
    //立即购买
    submit:function(e){
        let This = this;
        if(This.data.hasNumber == 0 || This.data.hasNumber==''){
            This.setData({
                hasNumber:1
            });
            Tools.showErrorToast('添加数量最少为一')
        }else{

            let currentSelectShop = This.data.selectShopDetailInfo;
            currentSelectShop['number'] = parseInt(This.data.hasNumber);//商品数量
            for (var tempIndex = 0;tempIndex < This.data.allType.length;tempIndex++) {
                if(This.data.allType[tempIndex].class == 'chose')
                {
                    //找到对应选中的那个规格
                    currentSelectShop["space_id"] = This.data.allType[tempIndex].space_id;
                    currentSelectShop["space_price"] = This.data.allType[tempIndex].space_price;
                    currentSelectShop["space_name"] = This.data.allType[tempIndex].space_name;
                    currentSelectShop["space_unit"] = This.data.allType[tempIndex].space_unit;
                    currentSelectShop["space_stock"] = This.data.allType[tempIndex].space_stock;
                    currentSelectShop["space_sold"] = This.data.allType[tempIndex].space_sold;
                    currentSelectShop['goods_id'] = This.data.chooseShopId
                    break;
                }
            }
            let data=[currentSelectShop];
            wx.navigateTo({
                url:'../mines/confirmationOrder/confirmationOrder?shopArray='+JSON.stringify(data)+'&shop_cart_ids='
            })
        }
    }
};
init(PageData);